package model.caret;

import model.code.line.LineList;

import java.util.ArrayList;

/**
 * This is just a reference to a {@link Caret} so that the {@link Caret} object can be changed without breaking references.
 *
 * @author Neil Dickson
 */
public class CaretRef {
	private	Caret						caret;
	private	ArrayList<CaretObserver>	observers;

	public CaretRef() {
		this(null);
	}
	public CaretRef(Caret caret) {
		this.caret = caret;
		observers = new ArrayList<CaretObserver>();
	}

	public void addObserver(CaretObserver observer) {
		if (observer==null) {
			throw new NullPointerException();
		}
		if (!observers.contains(observer)) {
			observers.add(observer);
		}
	}
	public synchronized void removeObserver(CaretObserver observer) {
		if (observers.contains(observer)) {
			observers.remove(observer);
		}
	}
	void updateAllBut(CaretObserver culprit) {
		for (CaretObserver observer : observers) {
			if (observer!=culprit) {
				observer.caretChanged(this);
			}
		}
	}
	void updateAll() {
		for (CaretObserver observer : observers) {
			observer.caretChanged(this);
		}
	}

	public Caret get() {
		return caret;
	}

	public void set(Caret caret) {
		this.caret = caret;
		updateAll();
	}

	public boolean isTextCaret() {
		return (caret!=null) && (caret instanceof TextCaret);
	}

	public boolean isTextCaret(LineList lines) {
		return (caret!=null) && (caret instanceof TextCaret) && (((TextCaret)caret).getLineList()==lines);
	}

	public boolean isHeaderCaret() {
		return (caret!=null) && (caret instanceof HeaderCaret);
	}
}
